package com.usermanage.controller;

import com.contract.Bean.ContractBean1;
import com.contract.Common.ContractIOC;
import com.contract.Common.SkuPriceTableIOC;
import com.contract.Common.TablePriceToCatalogIOC;
import com.contract.Service.TablePriceToCatalogService;
import com.ordercore.Util.ResponseData.ResponseData;
import com.ordercore.Util.Verify.pzDataVerifyUtil;
import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.SequenceService;
import com.usermanage.beanParam.PermissionBean;
import com.usermanage.util.DateUtil;
import com.usermanage.util.StaticUtil;
import com.usermanage.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 合同
 */
@Slf4j
@RestController
@RequestMapping("/contract")
public class ContractController {
@Resource
private SequenceService sequenceService;

    /**
     * 合同列表页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list.page", method = RequestMethod.GET)
    public ModelAndView list() throws Exception {
        ModelAndView mv = new ModelAndView();
        //获得用户登陆信息
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        //从用户登陆信息中获取用户权限列表
        List<PermissionBean> permissionBeanList = userDetail.getList();
        //判断用户具有的权限在界面展示
        for (PermissionBean bean : permissionBeanList) {
            if (bean.getPermission_url().equals("/contract/add.page")) {
                mv.addObject("add", true);
            }
            if (bean.getPermission_url().equals("/contract/approve.json")) {
                mv.addObject("approve", true);
            }
            if (bean.getPermission_url().equals("/contract/export.json")) {
                mv.addObject("export", true);
            }
            if (bean.getPermission_url().equals("/contract/detail.page")) {
                mv.addObject("detail", true);
            }
        }
        mv.setViewName("/contract/list");
        return mv;
    }

    /**
     * 合同列表
     *
     * @param key
     * @param page
     * @param limit
     * @param *     @return
     */
    @RequestMapping(value = "/contractSummaryList.json", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public ResponseData contractSummaryList(String key, int page, int limit) {
        String company_id ="";
        if("1".equals(SpringSecurityUtils.getCurrentUser().getCompany_id())){
            return  ContractIOC.contractSummaryList(key, page, limit,company_id);
        }else{
            return ContractIOC.contractSummaryList(key, page, limit,SpringSecurityUtils.getCurrentUser().getCompany_id());
        }

    }

    /**
     * 合同添加
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uptContractSummary.json", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResponseData uptContractSummary(String id, String stat) {
        Integer contract_id = Integer.valueOf(id);
        return ContractIOC.uptContractSummary(contract_id, stat);
    }

    /**
     * 添加合同页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add.page", method = RequestMethod.GET)
    public ModelAndView add() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("JDCOMPANY", StaticUtil.JDCOMPANY);
        mv.setViewName("/contract/add");
        return mv;
    }

    /**
     * 合同添加
     *
     * @param contractSummary
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addContractSummary.json", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResponseData addContractSummary(ContractBean1 contractSummary) {
        return ContractIOC.addContractSummary(contractSummary);
    }

    /**
     * 合同详情
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/detail.page", method = RequestMethod.GET)
    public ModelAndView detail(String id) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping(value = "/queryContractSummary.json", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public static ResponseData queryContractSummary(String id) {
        Integer contract_id = Integer.valueOf(id);
        return ContractIOC.findById(contract_id);
    }

    /**
     * 合同详情
     *
     * @param key
     * @param page
     * @param limit
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/contractSummaryDetailList.json", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public ResponseData contractSummaryDetailList(int page, int limit, String contract_id, String spu_code, String cls, String key) {
        Integer contract_id1 = Integer.valueOf(contract_id);
        return ContractIOC.contractSkuList(page, limit, contract_id1, spu_code, cls, key);
    }


    @RequestMapping(value = "/findOneContract.json", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public static ResponseData findOneContract(String companyB_id) {

        ContractBean1 contractBean = new ContractBean1();
        contractBean.setCompanyB_id(companyB_id);

        return ContractIOC.findOne(contractBean);
    }

    @RequestMapping(value = "/getCatalogByCompanyId.json", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public ResponseData getCatalogByCompanyId(String contract_id, String priceSummaryId) {
        if (pzDataVerifyUtil.isBlank(contract_id) || pzDataVerifyUtil.isBlank(priceSummaryId)) {
            return ResponseData.fail("合同ID或者价目表ID为空！");
        }
        Integer contract_id1 = Integer.valueOf(contract_id);
        Integer priceSummaryId1 = Integer.valueOf(priceSummaryId);
        return TablePriceToCatalogIOC.getCatalogByCompanyId(contract_id1, priceSummaryId1);
    }

    @RequestMapping(value = "/getSpuByCls3.json", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public ResponseData getSpuByCls3(String contract_id, String priceSummaryId, String cls3) {
        Integer priceSummaryId1 = Integer.valueOf(priceSummaryId);
        Integer contract_id1 = Integer.valueOf(contract_id);
        return TablePriceToCatalogIOC.getSpuByCls3(contract_id1, priceSummaryId1, cls3);
    }

    /**
     * 导出订单明细
     *
     * @param response
     * @throws IOException
     * @throws Exception
     */
//    @RequestMapping(value = "/export.json")
//    public void ExportExcel(HttpServletResponse response, String id) throws IOException, Exception {
//        Optional<ContractBean> optional = contractService.findById(Integer.valueOf(id));
//        String company_type;
//        if ("ration".equals(optional.get().getContract_type())) {
//            company_type = "定量";
//        } else if ("realTime".equals(optional.get().getContract_type())) {
//            company_type = "实时";
//        } else {
//            company_type = "未知";
//        }
//        List<ContractRealTimePriceBean> contractRealTimePriceBeans = new ArrayList<>();
//        if ("realTime".equals(optional.get().getContract_type())) {
//            contractRealTimePriceBeans = contractRealTimePriceService.getSkuBySkuCodeAndContractIdDetail(null, optional.get().getId().toString());
//        } else {
//            Map contractSku = StringUtil.JsonToMap(optional.get().getContract_sku());
//            contractRealTimePriceBeans = StringUtil.convertListMapToListBean((List<Map>) contractSku.get("sku"), ContractRealTimePriceBean.class);
//        }
//
//
//        // 第一步，创建一个webbook，对应一个Excel文件
//        HSSFWorkbook wb = new HSSFWorkbook();
//        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
//        HSSFSheet sheet = wb.createSheet("合同明细");
//        //列宽
//        sheet.setColumnWidth(0, 60 * 100);
//        sheet.setColumnWidth(1, 100 * 100);
//        sheet.setColumnWidth(2, 60 * 100);
//        sheet.setColumnWidth(3, 60 * 100);
//        sheet.setColumnWidth(5, 100 * 100);
//        sheet.setColumnWidth(4, 60 * 100);
//        sheet.setColumnWidth(6, 60 * 100);
//        sheet.setColumnWidth(7, 60 * 100);
//        sheet.setColumnWidth(8, 100 * 100);
//        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
//        HSSFCellStyle headstyle = wb.createCellStyle();
//        headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
//        headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
//        headstyle.setLocked(true);
//        headstyle.setWrapText(true);// 自动换行
//        HSSFRow row0 = sheet.createRow((int) 0);
//        row0.setHeight((short) 900);
//        HSSFCell cell0 = row0.createCell(0);
//        cell0.setCellValue(new HSSFRichTextString(optional.get().getPartyB() + "  合同明细"));
//        cell0.setCellStyle(headstyle);
//        /**
//         * 合并单元格
//         *    第一个参数：第一个单元格的行数（从0开始）
//         *    第二个参数：第二个单元格的行数（从0开始）
//         *    第三个参数：第一个单元格的列数（从0开始）
//         *    第四个参数：第二个单元格的列数（从0开始）
//         */
//        CellRangeAddress range = new CellRangeAddress(0, 0, 0, 8);
//        sheet.addMergedRegion(range);
//        HSSFRow row1 = sheet.createRow((int) 1);
//        row1.setHeight((short) 700);
//        CellRangeAddress range1 = new CellRangeAddress(1, 1, 1, 8);
//        sheet.addMergedRegion(range1);
//        HSSFCell cell1 = row1.createCell(1);
//        cell1.setCellValue(new HSSFRichTextString("  合同编号： " + optional.get().getContract_no() + "   合同名称： " + optional.get().getContract_name() + "   甲方名称： " + optional.get().getPartyA() + "  乙方名称： " + optional.get().getPartyB() + "\r\n" + "   预计合同金额： " + optional.get().getContract_price() + "   合作方式： " + company_type + "  生效时间： " + optional.get().getActive_time() + "  结束时间： " + optional.get().getEnd_time() + "  付款说明： " + optional.get().getPayment() + "  合同说明  " + optional.get().getContract_note()));
//        cell1.setCellStyle(headstyle);
//
////        HSSFRow row2 = sheet.createRow((int) 2);
////        row2.setHeight((short) 400);
////        CellRangeAddress range2 = new CellRangeAddress(2, 2, 1, 8);
////        sheet.addMergedRegion(range2);
////        HSSFCell cell2 = row2.createCell(2);
////        cell2.setCellValue(new HSSFRichTextString("   预计合同金额： " + optional.get().getContract_price() + "   合作方式： " + company_type + "  生效时间： " + optional.get().getActive_time() + "结束时间： " + optional.get().getEnd_time() + "  付款说明： " + optional.get().getPayment() + "  合同说明  " + optional.get().getContract_note()));
////        cell2.setCellStyle(headstyle);
//
//        HSSFRow row = sheet.createRow((int) 2);
//        // 第四步，创建单元格，并设置值表头 设置表头居中
//        HSSFCellStyle style = wb.createCellStyle();
//        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//        HSSFCell cell = row.createCell(0);
//        cell.setCellValue("材料编码");
//        cell.setCellStyle(style);
//        cell = row.createCell(1);
//        cell.setCellValue("材料名称");
//        cell.setCellStyle(style);
//        cell = row.createCell(2);
//        cell.setCellValue("品牌");
//        cell.setCellStyle(style);
//        cell = row.createCell(3);
//        cell.setCellValue("型号");
//        cell.setCellStyle(style);
//        cell = row.createCell(4);
//        cell.setCellValue("规格参数");
//        cell.setCellStyle(style);
//        cell = row.createCell(5);
//        cell.setCellValue("单位");
//        cell.setCellStyle(style);
//        cell = row.createCell(6);
//        cell.setCellValue("成本单价");
//        cell.setCellStyle(style);
//        cell = row.createCell(7);
//        cell.setCellValue("供货周期");
//        cell.setCellStyle(style);
//        cell = row.createCell(8);
//        cell.setCellValue("备注");
//        cell.setCellStyle(style);
//        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，
//
//        for (int i = 0; i < contractRealTimePriceBeans.size(); i++) {
//            row = sheet.createRow((int) 2 + 1 + i);
//
//            // 第四步，创建单元格，并设置值
//            row.createCell(0).setCellValue(contractRealTimePriceBeans.get(i).getSku_code() == null ? "" : contractRealTimePriceBeans.get(i).getSku_code());
//            row.createCell(1).setCellValue(contractRealTimePriceBeans.get(i).getSku_name() == null ? "" : contractRealTimePriceBeans.get(i).getSku_name());
//            row.createCell(2).setCellValue(contractRealTimePriceBeans.get(i).getSku_brand() == null ? "" : contractRealTimePriceBeans.get(i).getSku_brand());
//            row.createCell(3).setCellValue(contractRealTimePriceBeans.get(i).getSku_model() == null ? "" : contractRealTimePriceBeans.get(i).getSku_model());
//            row.createCell(4).setCellValue(contractRealTimePriceBeans.get(i).getSku_slug_set() == null ? "" : contractRealTimePriceBeans.get(i).getSku_slug_set());
//            row.createCell(5).setCellValue(contractRealTimePriceBeans.get(i).getSku_unit() == null ? "" : contractRealTimePriceBeans.get(i).getSku_unit());
//            row.createCell(6).setCellValue(contractRealTimePriceBeans.get(i).getSku_contract_price() == null ? "" : contractRealTimePriceBeans.get(i).getSku_contract_price());
//            row.createCell(7).setCellValue(contractRealTimePriceBeans.get(i).getSku_lead_time() == null ? "" : contractRealTimePriceBeans.get(i).getSku_lead_time());
//            row.createCell(8).setCellValue(contractRealTimePriceBeans.get(i).getSku_content() == null ? "" : contractRealTimePriceBeans.get(i).getSku_content());
//        }
//
//        // 第六步，将文件存到指定位置
//        try {
//            String filename = optional.get().getContract_name();
//            String fileName = new String(filename.getBytes(), "iso8859-1") + ".xls";
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-disposition", "attachment;filename="+ fileName);//默认Excel名称
//            response.flushBuffer();
//            response.setCharacterEncoding("UTF-8");
//            wb.write(response.getOutputStream());
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            wb.close();
//        }
//    }

}
